<template>
    <div class="training-review-page">
        <!-- 导航栏 -->
        <van-nav-bar title="Training Review" left-text="Home" left-arrow @click-left="goHome">
            <template #right>
                <van-icon name="share" @click="shareResults" />
            </template>
        </van-nav-bar>

        <!-- 训练总结卡片 -->
        <div class="summary-section">
            <div class="summary-card">
                <div class="summary-header">
                    <div class="character-info">
                        <van-image :src="character?.avatar_url || '/default-character.png'" width="60" height="60" round
                            fit="cover" />
                        <div class="character-details">
                            <h3>{{ character?.name }}</h3>
                            <p>{{ scenario?.title }}</p>
                        </div>
                    </div>
                    <div class="completion-badge">
                        <van-icon name="success" />
                        <span>Completed</span>
                    </div>
                </div>

                <div class="summary-stats">
                    <div class="stat-item">
                        <div class="stat-number">{{ formatTime(duration) }}</div>
                        <div class="stat-label">Duration</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">{{ messageCount }}</div>
                        <div class="stat-label">Messages</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">{{ overallScore }}</div>
                        <div class="stat-label">Score</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">{{ improvementPoints }}</div>
                        <div class="stat-label">Improvements</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 详细分析 -->
        <div class="analysis-section">
            <!-- 沟通技能评估 -->
            <div class="analysis-card">
                <div class="card-header">
                    <h3>Communication Skills Assessment</h3>
                    <van-icon name="chart-trending-o" />
                </div>
                <div class="skills-list">
                    <div v-for="skill in communicationSkills" :key="skill.name" class="skill-item">
                        <div class="skill-info">
                            <span class="skill-name">{{ skill.name }}</span>
                            <span class="skill-score">{{ skill.score }}/10</span>
                        </div>
                        <div class="skill-progress">
                            <van-progress :percentage="skill.score * 10" :color="getSkillColor(skill.score)"
                                stroke-width="6" />
                        </div>
                    </div>
                </div>
            </div>

            <!-- 关键亮点 -->
            <div class="analysis-card">
                <div class="card-header">
                    <h3>Key Highlights</h3>
                    <van-icon name="star-o" />
                </div>
                <div class="highlights-list">
                    <div v-for="highlight in keyHighlights" :key="highlight.id" class="highlight-item">
                        <van-icon name="success" />
                        <span>{{ highlight.text }}</span>
                    </div>
                </div>
            </div>

            <!-- 改进建议 -->
            <div class="analysis-card">
                <div class="card-header">
                    <h3>Areas for Improvement</h3>
                    <van-icon name="bulb-o" />
                </div>
                <div class="improvements-list">
                    <div v-for="improvement in improvementSuggestions" :key="improvement.id" class="improvement-item">
                        <div class="improvement-header">
                            <van-icon name="arrow-up" />
                            <span class="improvement-title">{{ improvement.title }}</span>
                        </div>
                        <p class="improvement-description">{{ improvement.description }}</p>
                        <div class="improvement-tips">
                            <span class="tips-label">Tips:</span>
                            <ul>
                                <li v-for="tip in improvement.tips" :key="tip">{{ tip }}</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 对话回顾 -->
            <div class="analysis-card">
                <div class="card-header">
                    <h3>Conversation Review</h3>
                    <van-icon name="chat-o" />
                </div>
                <div class="conversation-analysis">
                    <div class="analysis-metrics">
                        <div class="metric-item">
                            <span class="metric-label">Response Time</span>
                            <span class="metric-value">{{ averageResponseTime }}s avg</span>
                        </div>
                        <div class="metric-item">
                            <span class="metric-label">Message Length</span>
                            <span class="metric-value">{{ averageMessageLength }} words avg</span>
                        </div>
                        <div class="metric-item">
                            <span class="metric-label">Positive Feedback</span>
                            <span class="metric-value">{{ positiveFeedbackRate }}%</span>
                        </div>
                    </div>

                    <!-- 关键对话片段 -->
                    <div class="key-moments">
                        <h4>Key Conversation Moments</h4>
                        <div v-for="moment in keyMoments" :key="moment.id" class="moment-item">
                            <div class="moment-header">
                                <span class="moment-type" :class="moment.type">{{ moment.label }}</span>
                                <span class="moment-time">{{ moment.timestamp }}</span>
                            </div>
                            <div class="moment-content">
                                <div class="message ai-message">
                                    <strong>{{ character?.name }}:</strong> {{ moment.aiMessage }}
                                </div>
                                <div class="message user-message">
                                    <strong>You:</strong> {{ moment.userMessage }}
                                </div>
                            </div>
                            <div class="moment-analysis">
                                <p>{{ moment.analysis }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 行动建议 -->
        <div class="actions-section">
            <div class="actions-card">
                <h3>Next Steps</h3>
                <div class="action-buttons">
                    <van-button type="primary" size="large" block @click="practiceAgain">
                        <van-icon name="replay" />
                        Practice This Scenario Again
                    </van-button>

                    <van-button type="success" size="large" block @click="tryHarderScenario">
                        <van-icon name="arrow-up" />
                        Try a Harder Scenario
                    </van-button>

                    <van-button size="large" block @click="exploreOtherScenarios">
                        <van-icon name="search" />
                        Explore Other Scenarios
                    </van-button>

                    <van-button size="large" block @click="viewProgress">
                        <van-icon name="chart-trending-o" />
                        View Overall Progress
                    </van-button>
                </div>
            </div>
        </div>

        <!-- 分享弹窗 -->
        <van-popup v-model:show="showSharePopup" position="bottom" round>
            <div class="share-popup">
                <div class="popup-header">
                    <h3>Share Your Achievement</h3>
                    <van-icon name="cross" @click="showSharePopup = false" />
                </div>
                <div class="share-content">
                    <div class="achievement-preview">
                        <div class="preview-header">
                            <van-image :src="character?.avatar_url || '/default-character.png'" width="40" height="40"
                                round fit="cover" />
                            <div class="preview-info">
                                <h4>Completed Training Session</h4>
                                <p>{{ scenario?.title }} with {{ character?.name }}</p>
                            </div>
                        </div>
                        <div class="preview-stats">
                            <span>Score: {{ overallScore }}/10</span>
                            <span>Duration: {{ formatTime(duration) }}</span>
                        </div>
                    </div>
                    <div class="share-options">
                        <van-button block @click="shareToSocial('twitter')">
                            <van-icon name="share" />
                            Share to Twitter
                        </van-button>
                        <van-button block @click="shareToSocial('linkedin')">
                            <van-icon name="share" />
                            Share to LinkedIn
                        </van-button>
                        <van-button block @click="copyShareLink">
                            <van-icon name="link-o" />
                            Copy Link
                        </van-button>
                    </div>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { trainingApi, type AiCharacter, type TrainingScenario } from '@/api'

const router = useRouter()
const route = useRoute()

// 响应式数据
const character = ref<AiCharacter | null>(null)
const scenario = ref<TrainingScenario | null>(null)
const showSharePopup = ref(false)

// 从路由参数获取训练数据
const sessionId = computed(() => route.query.sessionId as string)
const duration = computed(() => parseInt(route.query.duration as string) || 0)
const messageCount = computed(() => parseInt(route.query.messageCount as string) || 0)

// 模拟分析数据
const communicationSkills = ref([
    { name: 'Active Listening', score: 8 },
    { name: 'Empathy', score: 7 },
    { name: 'Clarity', score: 9 },
    { name: 'Confidence', score: 6 },
    { name: 'Adaptability', score: 8 }
])

const keyHighlights = ref([
    { id: 1, text: 'Excellent use of clarifying questions' },
    { id: 2, text: 'Maintained professional tone throughout' },
    { id: 3, text: 'Showed good empathy and understanding' },
    { id: 4, text: 'Provided specific examples when needed' }
])

const improvementSuggestions = ref([
    {
        id: 1,
        title: 'Build Confidence',
        description: 'You showed some hesitation in your responses. Building confidence will help you communicate more effectively.',
        tips: [
            'Practice speaking with conviction',
            'Prepare key points in advance',
            'Use positive body language'
        ]
    },
    {
        id: 2,
        title: 'Response Timing',
        description: 'Some responses took longer than optimal. Work on thinking quickly while maintaining quality.',
        tips: [
            'Practice common scenarios regularly',
            'Develop go-to phrases for different situations',
            'Learn to pause thoughtfully rather than hesitate'
        ]
    }
])

const keyMoments = ref([
    {
        id: 1,
        type: 'excellent',
        label: 'Excellent Response',
        timestamp: '2:34',
        aiMessage: 'How do you think we should handle this challenging situation?',
        userMessage: 'I think we should first gather all the facts, then discuss possible solutions with the team.',
        analysis: 'Great structured approach! You showed logical thinking and collaborative mindset.'
    },
    {
        id: 2,
        type: 'improvement',
        label: 'Room for Improvement',
        timestamp: '5:12',
        aiMessage: 'What\'s your opinion on the proposed changes?',
        userMessage: 'Um, I think... maybe it could work?',
        analysis: 'This response lacked confidence. Try to be more decisive and provide specific reasoning.'
    }
])

// 计算属性
const overallScore = computed(() => {
    const avgSkillScore = communicationSkills.value.reduce((sum, skill) => sum + skill.score, 0) / communicationSkills.value.length
    return Math.round(avgSkillScore * 10) / 10
})

const improvementPoints = computed(() => {
    return communicationSkills.value.filter(skill => skill.score < 7).length
})

const averageResponseTime = computed(() => {
    // 模拟计算平均响应时间
    return Math.round((duration.value / messageCount.value) * 10) / 10
})

const averageMessageLength = computed(() => {
    // 模拟计算平均消息长度
    return Math.floor(Math.random() * 20) + 15
})

const positiveFeedbackRate = computed(() => {
    // 模拟正面反馈率
    return Math.floor(Math.random() * 30) + 70
})

// 方法
const loadData = async () => {
    try {
        const characterId = route.query.characterId
        const scenarioId = route.query.scenarioId

        if (!characterId || !scenarioId) {
            showToast('Missing parameters')
            router.push({ name: 'Home' })
            return
        }

        // 加载角色和场景信息
        const [charactersResponse, scenariosResponse] = await Promise.all([
            trainingApi.getCharacters(),
            trainingApi.getScenarios()
        ])

        character.value = charactersResponse.data.find(
            char => char.id === parseInt(characterId as string)
        ) || null

        scenario.value = scenariosResponse.data.find(
            scen => scen.id === parseInt(scenarioId as string)
        ) || null

        // 保存训练记录
        await saveTrainingRecord()
    } catch (error) {
        console.error('Failed to load review data:', error)
        showToast('Failed to load review data')
    }
}

const saveTrainingRecord = async () => {
    try {
        // 这里应该调用API保存训练记录
        console.log('Saving training record:', {
            sessionId: sessionId.value,
            characterId: route.query.characterId,
            scenarioId: route.query.scenarioId,
            duration: duration.value,
            messageCount: messageCount.value,
            score: overallScore.value,
            skills: communicationSkills.value
        })
    } catch (error) {
        console.error('Failed to save training record:', error)
    }
}

const getSkillColor = (score: number) => {
    if (score >= 8) return '#07c160'
    if (score >= 6) return '#ffd21e'
    return '#ee0a24'
}

const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, '0')}`
}

const practiceAgain = () => {
    router.push({
        name: 'TrainingChat',
        query: {
            characterId: route.query.characterId,
            scenarioId: route.query.scenarioId
        }
    })
}

const tryHarderScenario = () => {
    // 寻找更难的场景
    router.push({
        name: 'ScenarioSelect',
        query: {
            characterId: route.query.characterId,
            difficulty: 'advanced'
        }
    })
}

const exploreOtherScenarios = () => {
    router.push({
        name: 'ScenarioSelect',
        query: {
            characterId: route.query.characterId
        }
    })
}

const viewProgress = () => {
    router.push({ name: 'Progress' })
}

const goHome = () => {
    router.push({ name: 'Home' })
}

const shareResults = () => {
    showSharePopup.value = true
}

const shareToSocial = (platform: string) => {
    const text = `Just completed a training session with ${character.value?.name}! Score: ${overallScore.value}/10 🎉`
    const url = window.location.href

    let shareUrl = ''
    if (platform === 'twitter') {
        shareUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(url)}`
    } else if (platform === 'linkedin') {
        shareUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`
    }

    if (shareUrl) {
        window.open(shareUrl, '_blank')
    }

    showSharePopup.value = false
}

const copyShareLink = async () => {
    try {
        await navigator.clipboard.writeText(window.location.href)
        showToast('Link copied to clipboard')
        showSharePopup.value = false
    } catch (error) {
        showToast('Failed to copy link')
    }
}

// 生命周期
onMounted(() => {
    loadData()
})
</script>

<style lang="scss" scoped>
.training-review-page {
    min-height: 100vh;
    background: #f7f8fa;
    padding-bottom: 20px;

    .summary-section {
        padding: 20px;

        .summary-card {
            background: white;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

            .summary-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 20px;

                .character-info {
                    display: flex;
                    gap: 16px;
                    align-items: center;

                    .character-details {
                        h3 {
                            font-size: 20px;
                            color: #323233;
                            margin: 0 0 4px 0;
                            font-weight: 600;
                        }

                        p {
                            font-size: 16px;
                            color: #646566;
                            margin: 0;
                        }
                    }
                }

                .completion-badge {
                    display: flex;
                    align-items: center;
                    gap: 6px;
                    padding: 8px 16px;
                    background: #e8f8f0;
                    border-radius: 20px;
                    color: #07c160;
                    font-size: 14px;
                    font-weight: 500;

                    .van-icon {
                        color: #07c160;
                    }
                }
            }

            .summary-stats {
                display: grid;
                grid-template-columns: repeat(4, 1fr);
                gap: 16px;

                .stat-item {
                    text-align: center;

                    .stat-number {
                        font-size: 24px;
                        font-weight: 600;
                        color: #1989fa;
                        margin-bottom: 4px;
                    }

                    .stat-label {
                        font-size: 12px;
                        color: #969799;
                    }
                }
            }
        }
    }

    .analysis-section {
        padding: 0 20px;

        .analysis-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 16px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);

            .card-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 16px;

                h3 {
                    font-size: 18px;
                    color: #323233;
                    margin: 0;
                    font-weight: 600;
                }

                .van-icon {
                    color: #1989fa;
                    font-size: 20px;
                }
            }

            .skills-list {
                .skill-item {
                    margin-bottom: 16px;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    .skill-info {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        margin-bottom: 8px;

                        .skill-name {
                            font-size: 15px;
                            color: #323233;
                        }

                        .skill-score {
                            font-size: 14px;
                            color: #646566;
                            font-weight: 500;
                        }
                    }

                    .skill-progress {
                        :deep(.van-progress) {
                            .van-progress__portion {
                                border-radius: 3px;
                            }
                        }
                    }
                }
            }

            .highlights-list {
                .highlight-item {
                    display: flex;
                    align-items: flex-start;
                    gap: 8px;
                    margin-bottom: 12px;
                    font-size: 15px;
                    color: #646566;
                    line-height: 1.5;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    .van-icon {
                        color: #07c160;
                        margin-top: 2px;
                        flex-shrink: 0;
                    }
                }
            }

            .improvements-list {
                .improvement-item {
                    padding: 16px;
                    background: #f7f8fa;
                    border-radius: 8px;
                    margin-bottom: 16px;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    .improvement-header {
                        display: flex;
                        align-items: center;
                        gap: 8px;
                        margin-bottom: 8px;

                        .van-icon {
                            color: #ffd21e;
                        }

                        .improvement-title {
                            font-size: 16px;
                            color: #323233;
                            font-weight: 500;
                        }
                    }

                    .improvement-description {
                        font-size: 14px;
                        color: #646566;
                        line-height: 1.5;
                        margin: 0 0 12px 0;
                    }

                    .improvement-tips {
                        .tips-label {
                            font-size: 14px;
                            color: #323233;
                            font-weight: 500;
                        }

                        ul {
                            margin: 4px 0 0 0;
                            padding-left: 16px;

                            li {
                                font-size: 13px;
                                color: #646566;
                                line-height: 1.4;
                                margin-bottom: 2px;
                            }
                        }
                    }
                }
            }

            .conversation-analysis {
                .analysis-metrics {
                    display: grid;
                    grid-template-columns: 1fr 1fr;
                    gap: 12px;
                    margin-bottom: 20px;

                    .metric-item {
                        padding: 12px;
                        background: #f7f8fa;
                        border-radius: 8px;
                        text-align: center;

                        .metric-label {
                            display: block;
                            font-size: 12px;
                            color: #969799;
                            margin-bottom: 4px;
                        }

                        .metric-value {
                            font-size: 16px;
                            color: #323233;
                            font-weight: 500;
                        }
                    }
                }

                .key-moments {
                    h4 {
                        font-size: 16px;
                        color: #323233;
                        margin: 0 0 16px 0;
                        font-weight: 500;
                    }

                    .moment-item {
                        padding: 16px;
                        background: #f7f8fa;
                        border-radius: 8px;
                        margin-bottom: 16px;

                        &:last-child {
                            margin-bottom: 0;
                        }

                        .moment-header {
                            display: flex;
                            justify-content: space-between;
                            align-items: center;
                            margin-bottom: 12px;

                            .moment-type {
                                padding: 4px 8px;
                                border-radius: 12px;
                                font-size: 12px;
                                font-weight: 500;

                                &.excellent {
                                    background: #e8f8f0;
                                    color: #07c160;
                                }

                                &.improvement {
                                    background: #fff7e6;
                                    color: #ffd21e;
                                }
                            }

                            .moment-time {
                                font-size: 12px;
                                color: #969799;
                            }
                        }

                        .moment-content {
                            margin-bottom: 12px;

                            .message {
                                padding: 8px 12px;
                                border-radius: 8px;
                                margin-bottom: 8px;
                                font-size: 14px;
                                line-height: 1.4;

                                &:last-child {
                                    margin-bottom: 0;
                                }

                                strong {
                                    color: #323233;
                                }

                                &.ai-message {
                                    background: white;
                                    border-left: 3px solid #1989fa;
                                }

                                &.user-message {
                                    background: #e8f4fd;
                                    border-left: 3px solid #07c160;
                                }
                            }
                        }

                        .moment-analysis {
                            p {
                                font-size: 13px;
                                color: #646566;
                                line-height: 1.4;
                                margin: 0;
                                font-style: italic;
                            }
                        }
                    }
                }
            }
        }
    }

    .actions-section {
        padding: 0 20px;

        .actions-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);

            h3 {
                font-size: 18px;
                color: #323233;
                margin: 0 0 20px 0;
                font-weight: 600;
                text-align: center;
            }

            .action-buttons {
                .van-button {
                    margin-bottom: 12px;
                    height: 48px;
                    font-size: 16px;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    .van-icon {
                        margin-right: 8px;
                    }
                }
            }
        }
    }

    .share-popup {
        padding: 24px;

        .popup-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;

            h3 {
                font-size: 18px;
                color: #323233;
                margin: 0;
                font-weight: 600;
            }

            .van-icon {
                color: #969799;
                cursor: pointer;
            }
        }

        .share-content {
            .achievement-preview {
                background: #f7f8fa;
                border-radius: 12px;
                padding: 16px;
                margin-bottom: 20px;

                .preview-header {
                    display: flex;
                    gap: 12px;
                    align-items: center;
                    margin-bottom: 12px;

                    .preview-info {
                        h4 {
                            font-size: 16px;
                            color: #323233;
                            margin: 0 0 4px 0;
                            font-weight: 500;
                        }

                        p {
                            font-size: 14px;
                            color: #646566;
                            margin: 0;
                        }
                    }
                }

                .preview-stats {
                    display: flex;
                    gap: 16px;
                    font-size: 14px;
                    color: #646566;
                }
            }

            .share-options {
                .van-button {
                    margin-bottom: 8px;
                    height: 44px;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    .van-icon {
                        margin-right: 8px;
                    }
                }
            }
        }
    }
}
</style>